﻿using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using HanumanInstitute.MvvmDialogs;
using TS2MP4.Models;
using TS2MP4.Services;
using Xabe.FFmpeg;

namespace TS2MP4.ViewModels;

internal partial class MainViewModel : ObservableObject
{
    private readonly IDialogService _dialogService;
    private readonly IOpenExplorerService _openExplorerService;

    [ObservableProperty] private string[] _dropFileData = [];
    [ObservableProperty] private int _finishedCount;

    [ObservableProperty] private string? _inPath;

    [ObservableProperty] private bool _isDeleteFiles;

    [ObservableProperty] private bool _isOpenExplorerWhenFinished;

    [ObservableProperty] private bool _isOverwriteOutput;

    public MainViewModel(IDialogService dialogService, IOpenExplorerService openExplorerService)
    {
        _dialogService = dialogService;
        _openExplorerService = openExplorerService;
        TsFiles.CollectionChanged += (_, _) => { ConvertCommand.NotifyCanExecuteChanged(); };
    }

    public ObservableCollection<TsFile> TsFiles { get; } = [];

    // ReSharper disable once UnusedParameterInPartialMethod
    partial void OnInPathChanged(string? value)
    {
        RefreshCommand.NotifyCanExecuteChanged();
    }

    [RelayCommand]
    private async Task DropFile()
    {
        if (DropFileData.Length > 0 && Directory.Exists(DropFileData[0]))
        {
            InPath = DropFileData[0];
            await LoadTsFilesFromDirectory(InPath);
        }
    }

    [RelayCommand]
    private async Task Browse()
    {
        using var folder = await _dialogService.ShowOpenFolderDialogAsync(this);
        if (folder != null)
        {
            InPath = folder.LocalPath;
            await LoadTsFilesFromDirectory(InPath);
        }
    }

    private async Task LoadTsFilesFromDirectory(string directoryPath)
    {
        if (TsFiles.Any()) TsFiles.Clear();
        var stringBuilder = new StringBuilder();
        foreach (var file in Directory.GetFiles(directoryPath, "*.ts"))
            try
            {
                TsFiles.Add(new TsFile(await FFmpeg.GetMediaInfo(file)));
            }
            catch (Exception ex)
            {
                stringBuilder.AppendLine(ex.Message);
            }

        if (stringBuilder.Length > 0)
            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>(stringBuilder.ToString()),
                "LoadFileErr");
    }

    private bool CanExecuteRefresh()
    {
        return !string.IsNullOrWhiteSpace(InPath) && Directory.Exists(InPath);
    }

    [RelayCommand(CanExecute = nameof(CanExecuteRefresh))]
    private async Task Refresh()
    {
        if (Directory.Exists(InPath)) await LoadTsFilesFromDirectory(InPath);
    }

    private bool CanExecuteConvert()
    {
        return TsFiles.Any();
    }

    [RelayCommand(CanExecute = nameof(CanExecuteConvert))]
    private async Task Convert()
    {
        var isDeleteFiles = IsDeleteFiles;
        var isOverwriteOutput = IsOverwriteOutput;
        var isOpenExplorerWhenFinished = IsOpenExplorerWhenFinished;
        FinishedCount = 0;
        foreach (var tsFile in TsFiles)
        {
            await Convert(tsFile, isOverwriteOutput);
            if (tsFile.Result is Result.Success or Result.Skipped && isDeleteFiles) File.Delete(tsFile.MediaInfo.Path);
            FinishedCount++;
        }

        if (TsFiles.Any() && Directory.Exists(InPath) && isOpenExplorerWhenFinished)
            _openExplorerService.OpenExplorer(InPath);
    }

    private static async Task Convert(TsFile tsFile, bool overwrite)
    {
        try
        {
            var mediaInfo = tsFile.MediaInfo;
            var output = Path.ChangeExtension(mediaInfo.Path, ".mp4");
            if (File.Exists(output) && !overwrite)
            {
                tsFile.Result = Result.Skipped;
            }
            else
            {
                var videoStream = mediaInfo.VideoStreams.First().SetCodec(VideoCodec.copy);
                var audioStream = mediaInfo.AudioStreams.First().SetCodec(AudioCodec.copy);
                await FFmpeg.Conversions.New()
                    .AddStream<IStream>(videoStream, audioStream)
                    .SetOutput(output)
                    .Start();
                tsFile.Result = Result.Success;
            }
        }
        catch (Exception ex)
        {
            tsFile.ErrorMessage = ex.Message;
        }
    }
}